//
//  LockSettingViewController.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2025/4/2.
//

#import "LockSettingViewController.h"
#import "CatSettingCell.h"
#import "CatSettingGroupModel.h"
#import "CatShareListViewController.h"

@interface LockSettingViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *settingTableview;
@property(nonatomic,strong)UIView *headerview;
@property(nonatomic,strong)UIView *footerview;
@property(nonatomic,strong)FBDevicesList *devicesList;
@property(nonatomic,copy)NSString *nickname;
@property(nonatomic,strong)NSMutableArray *dataArray;


@end

@implementation LockSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
    [self setup];
    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    self.settingTableview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
   
   [self getdata];
   [self.settingTableview reloadData];
}

- (void)setup
{
    self.view.backgroundColor = [UIColor whiteColor];
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,40,80);
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    
    [backbtn setImage:[UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
 
    UILabel *titleLabel  = [[UILabel alloc]init];
    titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20.0];
    titleLabel.text = NSLocalizedString(@"设置", nil);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.frame = CGRectMake(0, 0, 80, 25);
    self.navigationItem.titleView = titleLabel;
}

- (void)selectLeftActionClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)getdata{
    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
   
    [self.dataArray removeAllObjects];
     self.dataArray = nil;
  


    CatSettingGroupModel *groupModel2 = [[CatSettingGroupModel alloc]init];
    groupModel2.groupTitle = NSLocalizedString(@"通用设置",nil);
    
    CatSettingModel *model4_1 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"设备号",nil) subTitle:self.devicesList.name andType:0 status:NO];

   
    
    CatSettingModel *model4_2 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"当前网络",nil) subTitle:self.devicesList.wifi_ssid andType:0 status:NO];
  
    groupModel2.dataArray = @[model4_1,model4_2];
   
    
    CatSettingGroupModel *groupModel3 = [[CatSettingGroupModel alloc]init];
    groupModel3.groupTitle = NSLocalizedString(@"功能设置", nil);
   
    CatSettingModel *model5 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"设备分享", nil) subTitle:@"" andType:0 status:NO];
  
    CatSettingModel *model6 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"亮屏时间设置",nil) subTitle:[NSString stringWithFormat:@"%d秒",self.devicesList.lcd_timeout] andType:0 status:NO];

    CatSettingModel *model7 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"监控模式", nil) subTitle: self.devicesList.work_mode  == 1 ? @"已打开":@"已关闭" andType:0 status:NO];
    
    CatSettingModel *model8 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"安全密码设置", nil) subTitle:@"" andType:0 status:NO];
    
    CatSettingModel *model9 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"门铃系统升级", nil) subTitle:self.devicesList.remoteupg > 0 ?@"有新版本升级":@"已是最新版本" andType:0 status:NO];

    
    groupModel3.dataArray = @[model5,model6,model7,model8,model9];
    


    [self.dataArray addObject:groupModel2];
    [self.dataArray addObject:groupModel3];

    
     self.headerview.backgroundColor = [UIColor clearColor];
     self.footerview.backgroundColor = [UIColor clearColor];
    [self.settingTableview reloadData];
}






- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if(@available(iOS 15.0,*)){
      UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
      apperance.backgroundColor = [UIColor whiteColor];
      self.navigationController.navigationBar.standardAppearance = apperance;
      self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteDevices) name:@"deleteDevices" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDevicesNickname:) name:@"reloadNickname" object:nil];

}

- (void)deleteDevices
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}


//昵称改变 数据源重新更新
- (void)reloadDevicesNickname:(NSNotification *)notification
{
     self.devicesList.nick = self.nickname;
    [self.devicesList bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self getdata];
            [self.settingTableview reloadData];
        });
    }];
}


- (UITableView*)settingTableview
{
     if(!_settingTableview){
         _settingTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
         _settingTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
         _settingTableview.dataSource = self;
         _settingTableview.delegate = self;
         _settingTableview.tableHeaderView = self.headerview;
         _settingTableview.tableFooterView = self.footerview;
        [_settingTableview registerClass:[CatSettingCell class] forCellReuseIdentifier:@"CatSettingCell"];
         _settingTableview.rowHeight = 50;
        [self.view addSubview:_settingTableview];
        [_settingTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
    return _settingTableview;
}


- (UIView*)headerview
{
    if(!_headerview){
        _headerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth,160)];
        _headerview.backgroundColor = [UIColor  clearColor];
        UIImageView *deviceImage = [[UIImageView alloc]init];
        deviceImage.contentMode = UIViewContentModeCenter;
       [_headerview addSubview:deviceImage];
       [deviceImage mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerX.equalTo(_headerview.mas_centerX);
           make.top.equalTo(_headerview.mas_top).offset(13);
           make.width.height.mas_equalTo(102);
       }];
       deviceImage.image = [UIImage imageNamed:@"vl0_add_smart_lock"];
    }
    
    UIButton *button = (UIButton*)[_headerview viewWithTag:13156];
    if(button){
      [button removeFromSuperview];
       button = nil;
    }
    
    UIButton *editButon = [[UIButton alloc]init];
    editButon.tag = 13156;
    editButon.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16];
   [editButon setTitleColor:[HexChangeRGB colorWithHexString:@"#333333"] forState:UIControlStateNormal];
   [_headerview addSubview:editButon];
   [editButon mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerX.equalTo(_headerview.mas_centerX);
       make.top.equalTo(_headerview.mas_top).offset(125);
       make.height.mas_equalTo(22);
       make.width.mas_equalTo(280);
   }];
    [editButon setTitle:self.devicesList.nick.length > 0 ? self.devicesList.nick : NSLocalizedString(@"可视对讲智能锁", nil) forState:UIControlStateNormal];
    [editButon addTarget:self action:@selector(editButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [editButon setImage:[UIImage imageNamed:@"cat_setting_edit"] forState:UIControlStateNormal];
    [editButon SG_imagePositionStyle:SGImagePositionStyleRight spacing:5];
    return _headerview;
}

- (UIView*)footerview
{
    if(!_footerview){
        _footerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth,100)];
        _footerview.backgroundColor = [UIColor  clearColor];
    }
    
   UIButton *_deleteButton = [[UIButton alloc]init];
    _deleteButton.backgroundColor = [UIColor whiteColor];
   [_deleteButton setTitle:NSLocalizedString(@"删除设备", nil) forState:UIControlStateNormal];
    _deleteButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
   [_deleteButton setTitleColor:[HexChangeRGB colorWithHexString:@"#FF7316"] forState:UIControlStateNormal];
   [_deleteButton addTarget:self action:@selector(deleteButtonClick) forControlEvents:UIControlEventTouchUpInside];
   [_footerview addSubview:_deleteButton];
   [_deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerY.equalTo(_footerview.mas_centerY);
       make.height.mas_equalTo(44);
       make.width.mas_equalTo(260);
       make.centerX.equalTo(_footerview.mas_centerX);
   }];
   _deleteButton.layer.cornerRadius = 22;
   _deleteButton.layer.masksToBounds = YES;
   _deleteButton.layer.borderWidth = 1.0;
   _deleteButton.layer.borderColor = [HexChangeRGB colorWithHexString:@"#FF7316"].CGColor;

    return _footerview;
}

- (void)deleteButtonClick
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"确认删除设备", nil) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD show];
        [YKBusinessFramework equesDelDeviceWithBid:self.bid];
    }];
   
    [alertController addAction:cancelButton];
    [alertController addAction:deleteButton];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)editButtonClick
{
    

    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"修改名称", nil) message:NSLocalizedString(@"设备昵称不超过十个字符\n超过不显示", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
   UITextField *oldTf = [alert textFieldAtIndex:0];
   oldTf.tag = 199;
   oldTf.placeholder = NSLocalizedString(@"equipment_nickname_settings", nil);
   alert.tag = 100;
  [alert show];
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)//修改昵称
    {
        if (buttonIndex == 1)
        {
            
            NSLog(@"设备昵称 = %@",[alertView textFieldAtIndex:0].text);
            NSString *name = [alertView textFieldAtIndex:0].text;
            if (name.length >= 10) {
                NSRange range = {0,10};
                self.nickname = [[alertView textFieldAtIndex:0].text substringWithRange:range];
            }else {
                NSRange range = {0,name.length};
                self.nickname = [[alertView textFieldAtIndex:0].text substringWithRange:range];
            }
            
            if (![Tooles isValidateNick:[[alertView textFieldAtIndex:0].text stringByReplacingOccurrencesOfString:@" " withString:@""]])
            {
                if ([alertView textFieldAtIndex:0].text.length == 0)
                {
                    UIAlertView *alertEmptyView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"输入设备昵称", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
                     alertEmptyView.tag = 101;
                    [alertEmptyView show];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"请输入中文,字母,数字或下划线", nil) duration:2];
                }
                return;
            }
            else
            {
                [YKBusinessFramework equesSetDeviceNickWithBid:self.bid Nick:self.nickname];
            }
        }
        else
        {
            [self.settingTableview reloadData];
             NSLog(@"取消修改设备昵称");
        }
    }

}


- (NSMutableArray*)dataArray
{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CatSettingGroupModel *model = self.dataArray[section];
    return model.dataArray.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    CatSettingGroupModel *model = self.dataArray[indexPath.section];
    CatSettingModel  *datamodel = model.dataArray[indexPath.row];
    CatSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatSettingCell" forIndexPath:indexPath];
    cell.deleteBlock = ^(CatSettingModel * _Nonnull model) {
        
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"确定删除设备", nil) preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [SVProgressHUD show];
                [YKBusinessFramework equesDelDeviceWithBid:self.bid];
            }];
           
            [alertController addAction:cancelButton];
            [alertController addAction:deleteButton];
            [self presentViewController:alertController animated:YES completion:nil];
    };

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = datamodel;
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    CatSettingGroupModel *model = self.dataArray[indexPath.section];
    CatSettingModel  *datamodel = model.dataArray[indexPath.row];
   
    if([datamodel.title isEqualToString:NSLocalizedString(@"设备分享", nil)]){
        
        if (self.devicesList.is_share == 1) {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"子用户无法在分享设备",nil) duration:2];
             return;
        }
        
        CatShareListViewController *sharevc = [[CatShareListViewController alloc]init];
        sharevc.bid = self.bid;
       [self.navigationController pushViewController:sharevc animated:YES];

    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"亮屏时间设置", nil)]){
        
        
        [SVProgressHUD showWithDuration:10];
        FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];

        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
       [dict setValue:[NSString stringWithFormat:@"%d",15] forKey:@"lcd_timeout"];
       [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:self.bid] errorHint:^(id errorData) {
           [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed. Please try again later", nil)];
       }deleteDic:dict isFavorite:YES result:^(id data) {
              NSLog(@"show_open_lock_button data-->%@",data);
             [SVProgressHUD dismiss];
             if ([[data objectForKey:@"code"] intValue] == 0)
             {
                 if (list.status != 0) {
                     
                      NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                     [YKBusinessFramework equesSendData:Str];
                 }
                 [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:1.5];
                 
                 FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                 list.lcd_timeout = 15;
                [list bg_saveOrUpdate];
                [self getdata];
                [self.settingTableview reloadData];
             }else{
                 
                [self getdata];
                [self.settingTableview reloadData];
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
                 
             }
       }];
        
        
        
    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"监控模式", nil)]){
        
        
        [SVProgressHUD showWithDuration:10];
        FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];

        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:[NSString stringWithFormat:@"%d",!list.work_mode] forKey:@"work_mode"];
        [dict setValue:[NSString stringWithFormat:@"00:00"] forKey:@"alive_start_time"];
        [dict setValue:[NSString stringWithFormat:@"23:59"] forKey:@"alive_stop_time"];
       [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:self.bid] errorHint:^(id errorData) {
           [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed. Please try again later", nil)];
       }deleteDic:dict isFavorite:YES result:^(id data) {
              NSLog(@"show_open_lock_button data-->%@",data);
             [SVProgressHUD dismiss];
             if ([[data objectForKey:@"code"] intValue] == 0)
             {
                 if (list.status != 0) {
                     
                      NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                     [YKBusinessFramework equesSendData:Str];
                 }
                 [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:1.5];
                 
                 FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                 list.work_mode = !list.work_mode;
                [list bg_saveOrUpdate];
                [self getdata];
             }else{
                 
                [self getdata];
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
                 
             }
       }];
        
        
        
    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"安全密码设置", nil)]){
        
        
    }else if ([datamodel.title isEqualToString:NSLocalizedString(@"门铃系统升级", nil)]){
        
        
    }
    
}


@end
